const connection = require('../app/database');

class SecretService {

  // 创建一个密保问题
  async create(userId, question, answer) {
    try {
      const statement = `INSERT INTO secret (user_id, question, answer) VALUES (?, ?, ?)`;
      const result = await connection.execute(statement, [userId, question, answer]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 删除一个密保问题
  async remove(userId, secretId) {
    try {
      const statement = `DELETE FROM secret WHERE user_id = ? AND id = ?`;
      const result = await connection.execute(statement, [userId, secretId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 更新一个密保问题
  async update(userId, secretId, question, answer) {
    try {
      const statement = `UPDATE secret SET question = ?, answer = ? WHERE user_id = ? AND id = ?`;
      const result = await connection.execute(statement, [question, answer, userId, secretId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 返回密保列表
  async list(nickname) {
    try {
      const statement = `
                        SELECT 
                          s.id id,
                          s.question question,
                          s.user_id userId
                          FROM user u
                        LEFT JOIN secret s ON s.user_id = u.id
                        WHERE u.nickname = ?`;
      const result = await connection.execute(statement, [nickname]);
      return result[0];
    } catch (error) {
      console.log(error)
    }
  }

  // 验证密保问题是否正确
  async verify(secretId, answer) {
    try {
      const statement = `SELECT * FROM secret WHERE id = ? AND answer = ?`;
      const result = await connection.execute(statement, [secretId, answer]);
      return result[0].length === 0 ? false : true;
    } catch (error) {
      console.log(error);
    }
  }

  // 用户密保管理
  async getSecretList(userId){
    try {
      const statement = `
                        SELECT 
                          id 'key',
                          question,
                          answer,
                          createAt createTime
                        FROM secret
                        WHERE secret.user_id = ?`;
      const result = await connection.execute(statement, [userId]);
      return result[0];
    } catch (error) {
      console.log(error)
    }
  }

}

module.exports = new SecretService();
